﻿using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Xml;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    ///
    /// </summary>
    public static class LicenseProviderExtensions
    {
        private const string LgbLicenseFileName = "Longbow.lic";
        /// <summary>
        /// 增加CacheManager跨站点管理中间件
        /// </summary>
        /// <param name="builder"></param>
        public static IApplicationBuilder UseLicenseProvider(this IApplicationBuilder builder)
        {
            return builder.MapWhen(context => context.Request.Path == "/LicenseProvider.axd", app => app.Run(async context =>
            {
                var data = GetLicenseFromLicFile();
                await context.Response.WriteAsync(data ?? string.Empty);
            }));
        }

        private static string GetLicenseFromLicFile()
        {
            var licFile = Path.Combine(AppContext.BaseDirectory, LgbLicenseFileName);
            if (File.Exists(licFile))
            {
                var doc = new XmlDocument();
                try
                {
                    doc.Load(licFile);
                    return doc.ChildNodes[0].ChildNodes[0].InnerText;
                }
                catch { }
            }
            return null;
        }
    }
}
